<?php

namespace App\Console\Commands;

use App\Postings;
use Illuminate\Console\Command;

class AutoPostings extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'postings:autopostings';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '自动展示帖子和加精帖子';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->check();
        $time = time();
        $date = date('Y-m-d H:i:s', $time);
        //找到应展示的帖子
        $view_postings = Postings::where('view_time', '!=', null)->where('is_view', Postings::VIEW_NO)->where('view_time','<=', $date)->update(['is_view' => Postings::VIEW_YES, 'pub_time' => $date]);
        $hot_postings = Postings::where('hot_time', '!=', null)->where('is_hot', Postings::HOT_NO)->where('hot_time','<=', $date)->update(['is_hot' => Postings::HOT_YES]);
        exit('ok');
    }

    public function check()
    {
        $file = 'auto_postings.lock';
        $lock_file = storage_path($file);
        if (!flock($this->fp = fopen($lock_file, 'w'), LOCK_NB | LOCK_EX)) {
            //无法取得锁就退出
            logger($this->description . ' 脚本尝试重复启动');
            die('cannot get lock，already running?');
        }
        register_shutdown_function('unlink', $lock_file);
    }
}
